package main

import (
	"fmt"
	"sync"
	"time"
)

func main() {
	// channel()
	// bufferChannel()
	// channelClose()
	channelGroup()
}

func channel() {
	var channles [10]chan int

	for i := 0; i < 10; i++ {
		channles[i] = make(chan int)
		go get(i, channles[i])
	}

	for i := 0; i < 10; i++ {
		channles[i] <- i + 1
	}

	time.Sleep(1 * time.Second)
}

func get(id int, c chan int) {
	for i := range c {
		// 这里也可以使用 i, ok := <-c  判断是否关闭
		fmt.Printf("goroutine %d get %d\n", id, i)
	}

}

func bufferChannel() {
	c := make(chan int, 5)
	go get(0, c)
	c <- 1
	c <- 2
	c <- 3
	time.Sleep(1 * time.Second)
}

func channelClose() {
	c := make(chan int, 5)
	go get(0, c)
	c <- 0
	c <- 1
	c <- 2
	c <- 3
	close(c)
	time.Sleep(1 * time.Millisecond)
}

func work(c chan int, wg *sync.WaitGroup) {
	for i := range c {
		// 这里也可以使用 i, ok := <-c  判断是否关闭
		fmt.Printf("goroutine get %d\n", i)
		wg.Done()
	}

}

func channelGroup() {
	var wg sync.WaitGroup
	c := make(chan int, 5)
	go work(c, &wg)
	wg.Add(4)
	c <- 0
	c <- 1
	c <- 2
	c <- 3
	wg.Wait()
}
